<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>步态分析系统 - 用户控制台</title>
    <link rel="stylesheet" href="https://unpkg.com/element-plus/dist/index.css">
    <script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js"></script>
    <style>
        :root {
            --primary-color: #409EFF;
            --success-color: #67C23A;
            --warning-color: #E6A23C;
            --danger-color: #F56C6C;
            --text-color: #303133;
            --border-color: #DCDFE6;
        }

        body {
            margin: 0;
            padding: 0;
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
            background: linear-gradient(135deg, #f5f7fa 0%, #e4e7eb 100%);
            color: var(--text-color);
            min-height: 100vh;
        }

        .user-container {
            padding: 20px;
            max-width: 1400px;
            margin: 0 auto;
        }

        .header {
            background: linear-gradient(to right, var(--primary-color), var(--success-color));
            padding: 0 20px;
            height: 60px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            color: white;
            margin-bottom: 20px;
        }

        .control-card {
            background: white;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
        }

        .monitor-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 20px;
            margin-bottom: 20px;
        }

        .monitor-card {
            background: white;
            border-radius: 8px;
            padding: 20px;
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
        }

        .chart-container {
            height: 300px;
            margin-top: 20px;
        }

        .parameter-form {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
        }

        .result-card {
            margin-top: 20px;
            padding: 20px;
            border-radius: 8px;
            background: #f8f9fa;
            border-left: 4px solid var(--primary-color);
        }

        .status-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 15px;
        }

        .status-item {
            padding: 15px;
            background: #f5f7fa;
            border-radius: 6px;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .motor-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 15px;
            margin-top: 15px;
        }

        .motor-item {
            padding: 15px;
            background: #f5f7fa;
            border-radius: 6px;
            text-align: center;
        }
    </style>
</head>
<body>
    <div class="header">
        <h2>步态分析系统 - 用户控制台</h2>
        <div class="user-info">
            <span id="username">用户</span>
            <el-button type="text" style="color: white;" @click="handleLogout">退出登录</el-button>
        </div>
    </div>

    <div class="user-container">
        <el-tabs v-model="activeTab">
            <!-- 步态参数生成标签页 -->
            <el-tab-pane label="步态参数生成" name="gait">
                <div class="control-card">
                    <h3>步态参数设置</h3>
                    <el-form :model="gaitParams" label-width="120px" class="parameter-form">
                        <el-form-item label="步幅(mm)">
                            <el-input-number v-model="gaitParams.stride_length" :min="0" :max="500"></el-input-number>
                        </el-form-item>
                        <el-form-item label="步高(mm)">
                            <el-input-number v-model="gaitParams.step_height" :min="0" :max="300"></el-input-number>
                        </el-form-item>
                        <el-form-item label="时间间隔(s)">
                            <el-input-number v-model="gaitParams.time_interval" :min="0.1" :max="10" :step="0.1"></el-input-number>
                        </el-form-item>
                        <el-form-item label="点数">
                            <el-input-number v-model="gaitParams.point_count" :min="10" :max="2000"></el-input-number>
                        </el-form-item>
                    </el-form>
                    <div style="margin-top: 20px;">
                        <el-button type="primary" @click="generateGait">生成参数</el-button>
                        <el-button @click="resetParams">重置</el-button>
                    </div>

                    <div v-if="gaitResult" class="result-card">
                        <h4>生成结果</h4>
                        <el-descriptions :column="2" border>
                            <el-descriptions-item label="步幅">{{ gaitResult.stride_length }}mm</el-descriptions-item>
                            <el-descriptions-item label="步高">{{ gaitResult.step_height }}mm</el-descriptions-item>
                            <el-descriptions-item label="时间间隔">{{ gaitResult.time_interval }}s</el-descriptions-item>
                            <el-descriptions-item label="点数">{{ gaitResult.point_count }}</el-descriptions-item>
                            <el-descriptions-item label="结果">
                                <el-tag :type="gaitResult.result === '正常' ? 'success' : 'danger'">
                                    {{ gaitResult.result }}
                                </el-tag>
                            </el-descriptions-item>
                        </el-descriptions>
                    </div>
                </div>
            </el-tab-pane>

            <!-- 实时监控标签页 -->
            <el-tab-pane label="实时监控" name="monitor">
                <div class="monitor-grid">
                    <!-- 电池状态卡片 -->
                    <div class="monitor-card">
                        <h3>电池状态</h3>
                        <div class="status-grid">
                            <div class="status-item">
                                <span>电池电量</span>
                                <el-progress 
                                    :percentage="robotStatus.battery_level"
                                    :color="getBatteryColor"
                                ></el-progress>
                            </div>
                            <div class="status-item">
                                <span>电池电压</span>
                                <span>{{ robotStatus.battery_voltage }}V</span>
                            </div>
                            <div class="status-item">
                                <span>电池温度</span>
                                <span>{{ robotStatus.battery_temperature }}°C</span>
                            </div>
                        </div>
                    </div>

                    <!-- 系统状态卡片 -->
                    <div class="monitor-card">
                        <h3>系统状态</h3>
                        <div class="status-grid">
                            <div class="status-item">
                                <span>系统温度</span>
                                <span>{{ robotStatus.temperature }}°C</span>
                            </div>
                            <div class="status-item">
                                <span>CPU使用率</span>
                                <el-progress :percentage="robotStatus.cpu_usage"></el-progress>
                            </div>
                            <div class="status-item">
                                <span>内存使用率</span>
                                <el-progress :percentage="robotStatus.memory_usage"></el-progress>
                            </div>
                            <div class="status-item">
                                <span>运行状态</span>
                                <el-tag :type="getStatusType(robotStatus.running_status)">
                                    {{ robotStatus.running_status }}
                                </el-tag>
                            </div>
                        </div>
                    </div>

                    <!-- 电机状态卡片 -->
                    <div class="monitor-card">
                        <h3>电机状态</h3>
                        <el-tabs>
                            <el-tab-pane label="温度">
                                <div class="motor-grid">
                                    <div v-for="(temp, index) in robotStatus.motor_temperatures" :key="'temp'+index" class="motor-item">
                                        <span>电机{{ index + 1 }}: {{ temp }}°C</span>
                                    </div>
                                </div>
                            </el-tab-pane>
                            <el-tab-pane label="电流">
                                <div class="motor-grid">
                                    <div v-for="(current, index) in robotStatus.motor_currents" :key="'current'+index" class="motor-item">
                                        <span>电机{{ index + 1 }}: {{ current }}A</span>
                                    </div>
                                </div>
                            </el-tab-pane>
                            <el-tab-pane label="速度">
                                <div class="motor-grid">
                                    <div v-for="(speed, index) in robotStatus.motor_speeds" :key="'speed'+index" class="motor-item">
                                        <span>电机{{ index + 1 }}: {{ speed }}rad/s</span>
                                    </div>
                                </div>
                            </el-tab-pane>
                        </el-tabs>
                    </div>

                    <!-- IMU数据卡片 -->
                    <div class="monitor-card">
                        <h3>IMU数据</h3>
                        <div class="status-grid">
                            <div class="status-item">
                                <span>加速度X</span>
                                <span>{{ robotStatus.imu_data?.acc[0] || 0 }} m/s²</span>
                            </div>
                            <div class="status-item">
                                <span>加速度Y</span>
                                <span>{{ robotStatus.imu_data?.acc[1] || 0 }} m/s²</span>
                            </div>
                            <div class="status-item">
                                <span>加速度Z</span>
                                <span>{{ robotStatus.imu_data?.acc[2] || 0 }} m/s²</span>
                            </div>
                            <div class="status-item">
                                <span>角速度X</span>
                                <span>{{ robotStatus.imu_data?.gyro[0] || 0 }} °/s</span>
                            </div>
                            <div class="status-item">
                                <span>角速度Y</span>
                                <span>{{ robotStatus.imu_data?.gyro[1] || 0 }} °/s</span>
                            </div>
                            <div class="status-item">
                                <span>角速度Z</span>
                                <span>{{ robotStatus.imu_data?.gyro[2] || 0 }} °/s</span>
                            </div>
                        </div>
                    </div>
                </div>
            </el-tab-pane>

            <!-- 运动控制标签页 -->
            <el-tab-pane label="运动控制" name="control">
                <div class="control-card">
                    <h3>基本控制</h3>
                    <el-form :model="controlParams" label-width="120px">
                        <el-form-item label="步态类型">
                            <el-select v-model="controlParams.gait_type" placeholder="请选择步态类型">
                                <el-option label="行走" value="walk"></el-option>
                                <el-option label="跑步" value="run"></el-option>
                                <el-option label="爬楼梯" value="climb"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="速度">
                            <el-slider v-model="controlParams.speed" :min="0" :max="100"></el-slider>
                        </el-form-item>
                        <el-form-item label="方向">
                            <el-radio-group v-model="controlParams.direction">
                                <el-radio label="forward">前进</el-radio>
                                <el-radio label="backward">后退</el-radio>
                                <el-radio label="left">左转</el-radio>
                                <el-radio label="right">右转</el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="sendControl">发送控制指令</el-button>
                            <el-button type="danger" @click="emergencyStop">紧急停止</el-button>
                        </el-form-item>
                    </el-form>
                </div>
            </el-tab-pane>

            <!-- 历史记录标签页 -->
            <el-tab-pane label="历史记录" name="history">
                <div class="control-card">
                    <h3>步态参数记录</h3>
                    <el-table :data="gaitHistory">
                        <el-table-column prop="created_at" label="时间" width="180"></el-table-column>
                        <el-table-column prop="stride_length" label="步幅(mm)"></el-table-column>
                        <el-table-column prop="step_height" label="步高(mm)"></el-table-column>
                        <el-table-column prop="time_interval" label="时间间隔(s)"></el-table-column>
                        <el-table-column prop="point_count" label="点数"></el-table-column>
                        <el-table-column prop="result" label="结果">
                            <template #default="scope">
                                <el-tag :type="scope.row.result === '正常' ? 'success' : 'danger'">
                                    {{ scope.row.result }}
                                </el-tag>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </el-tab-pane>
        </el-tabs>
    </div>

    <script src="https://unpkg.com/vue@3.3.4/dist/vue.global.prod.js"></script>
    <script src="https://unpkg.com/element-plus"></script>
    <script src="https://unpkg.com/@element-plus/icons-vue"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>

    <script>
        const { createApp, ref, onMounted } = Vue;
        const app = createApp({
            setup() {
                const activeTab = ref('gait');
                const gaitParams = ref({
                    stride_length: 100,
                    step_height: 30,
                    time_interval: 0.5,
                    point_count: 100
                });
                const gaitResult = ref(null);
                const robotStatus = ref({
                    battery_level: 0,
                    battery_voltage: 24.0,
                    battery_temperature: 25.0,
                    temperature: 25.0,
                    cpu_usage: 0,
                    memory_usage: 0,
                    running_status: 'standby',
                    motor_temperatures: [25.0, 25.0, 25.0, 25.0],
                    motor_currents: [0.0, 0.0, 0.0, 0.0],
                    motor_speeds: [0.0, 0.0, 0.0, 0.0],
                    imu_data: {
                        acc: [0.0, 0.0, 0.0],
                        gyro: [0.0, 0.0, 0.0]
                    }
                });
                const controlParams = ref({
                    gait_type: 'walk',
                    speed: 50,
                    direction: 'forward'
                });
                const gaitHistory = ref([]);

                // 生成步态参数
                const generateGait = async () => {
                    try {
                        const response = await axios.post('/api/user/motion/control', {
                            ...gaitParams.value,
                            gait_type: controlParams.value.gait_type,
                            speed: controlParams.value.speed,
                            direction: controlParams.value.direction
                        });
                        if (response.data.message) {
                            gaitResult.value = response.data.data;
                            ElMessage.success(response.data.message);
                            fetchGaitHistory();
                        } else {
                            ElMessage.error(response.data.message || '生成参数失败');
                        }
                    } catch (error) {
                        console.error('生成参数失败:', error);
                        ElMessage.error(error.response?.data?.message || '生成参数失败');
                    }
                };

                // 重置参数
                const resetParams = () => {
                    gaitParams.value = {
                        stride_length: 100,
                        step_height: 30,
                        time_interval: 0.5,
                        point_count: 100
                    };
                    gaitResult.value = null;
                };

                // 获取机器人状态
                const fetchRobotStatus = async () => {
                    try {
                        const response = await axios.get('/api/robot/status');
                        robotStatus.value = response.data;
                    } catch (error) {
                        console.error('获取状态失败:', error);
                    }
                };

                // 发送控制指令
                const sendControl = async () => {
                    try {
                        await axios.post('/api/user/robot/control', controlParams.value);
                        ElMessage.success('控制指令已发送');
                    } catch (error) {
                        console.error('发送控制指令失败:', error);
                        ElMessage.error('发送控制指令失败');
                    }
                };

                // 紧急停止
                const emergencyStop = async () => {
                    try {
                        await axios.post('/api/user/robot/control', {
                            gait_type: 'stop',
                            speed: 0,
                            direction: 'stop'
                        });
                        ElMessage.success('紧急停止指令已发送');
                    } catch (error) {
                        console.error('发送紧急停止指令失败:', error);
                        ElMessage.error('发送紧急停止指令失败');
                    }
                };

                // 获取历史记录
                const fetchGaitHistory = async () => {
                    try {
                        const response = await axios.get('/api/refresh_data');
                        gaitHistory.value = response.data.data;
                    } catch (error) {
                        console.error('获取历史记录失败:', error);
                        ElMessage.error('获取历史记录失败');
                    }
                };

                // 获取电池颜色
                const getBatteryColor = (percentage) => {
                    if (percentage < 20) return '#F56C6C';
                    if (percentage < 50) return '#E6A23C';
                    return '#67C23A';
                };

                // 获取状态类型
                const getStatusType = (status) => {
                    const types = {
                        'running': 'success',
                        'standby': 'info',
                        'error': 'danger',
                        'warning': 'warning'
                    };
                    return types[status] || 'info';
                };

                // 退出登录
                const handleLogout = () => {
                    localStorage.removeItem('token');
                    localStorage.removeItem('isAdmin');
                    localStorage.removeItem('username');
                    window.location.href = 'login.html';
                };

                onMounted(async () => {
                    // 验证用户身份
                    const token = localStorage.getItem('token');
                    const isAdmin = localStorage.getItem('isAdmin') === 'true';
                    
                    if (!token || isAdmin) {
                        ElMessage.error('请先登录');
                        window.location.href = 'login.html';
                        return;
                    }

                    // 获取初始数据
                    await Promise.all([
                        fetchRobotStatus(),
                        fetchGaitHistory()
                    ]);

                    // 设置定时刷新
                    setInterval(fetchRobotStatus, 5000);
                });

                return {
                    activeTab,
                    gaitParams,
                    gaitResult,
                    robotStatus,
                    controlParams,
                    gaitHistory,
                    generateGait,
                    resetParams,
                    sendControl,
                    emergencyStop,
                    getBatteryColor,
                    getStatusType,
                    handleLogout
                };
            }
        });

        app.use(ElementPlus);
        app.mount('.user-container');
    </script>
</body>
</html> 